package com.bidianying.service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.bidianying.dao.GewaraDao;
import com.bidianying.dao.MaizuoDao;
import com.bidianying.util.LoadProperties;

@Service
public class MaizuoService {
	
	@Autowired
	private GewaraDao gewaraDao;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private MaizuoDao maizuoDao;


	public int saveMovieInfo(){
		String url = LoadProperties.getProperty("/config.properties", "maizuoDetailMovie");
		ResponseEntity<String> resultStr=null;
		Map<String,String> resultMap = new HashMap<String,String>();
		try{
			HttpHeaders requestHeaders = new HttpHeaders();  
			requestHeaders.set("Accept-Charset", "utf-8");  
			requestHeaders.set("Content-type", "text/xml; charset=utf-8");
			requestHeaders.add("Cookie", "mzCityId=10");
			HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
			resultStr = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
		JSONObject jsonObject=null;
		try{
			jsonObject = JSONObject.fromObject(resultStr.getBody());
		}catch(JSONException e){
			e.printStackTrace();
			return 0;
		}
		if(jsonObject.getInt("status")!=0){
			return 0;
		}
		JSONArray jsonArray = jsonObject.getJSONArray("data");
		for(int i = 0;i<jsonArray.size();i++){
			resultMap.put(jsonArray.getJSONObject(i).getString("movieId"),jsonArray.getJSONObject(i).getString("name"));
		}
		Set<String> resultMapKey = resultMap.keySet();
		Set<String> deleteKey = new HashSet<String>();
		for(String key : resultMapKey){
			String movieName = resultMap.get(key);
			if(movieName.contains("（3D）")){
				movieName = movieName.split("（3D）")[0];
			}
			deleteKey.add(movieName);
		}
		for(String key : deleteKey){
			resultMap.remove(key);
		}
		Map<String,String> gewaraMovieMap = gewaraDao.getAllGewaraMovieInfo();
		List<Map<String,String>> maizuoMovieList = new ArrayList<Map<String,String>>();
		Set<String> maizuoMapKey = resultMap.keySet();
		for(String key : maizuoMapKey){
			String movieName = resultMap.get(key);
			if(movieName.contains("（3D）")){
				movieName = movieName.split("（3D）")[0];
			}
			if(gewaraMovieMap.containsKey(movieName)){
				Map<String,String> map = new HashMap<String,String>();
				map.put("maizuoMovieId", key);
				map.put("maizuoMovieName", resultMap.get(key));
				map.put("id", gewaraMovieMap.get(movieName));
				maizuoMovieList.add(map);
			}
		}
		return maizuoDao.updateMovieInfoForMaizuo(maizuoMovieList);
	}
	
	
	public int saveMaizuoCityInfo(){
		String url = LoadProperties.getProperty("/config.properties", "maizuoCity");
		String resultStr = "";
		try{
			resultStr = restTemplate.getForObject(url, String.class);
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
		JSONArray jsonArray = null;
		try{
			jsonArray = JSONArray.fromObject(resultStr);
		}catch(JSONException e){
			e.printStackTrace();
			return 0;
		}
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		for(int i = 0;i<jsonArray.size();i++){
			JSONObject obj = jsonArray.getJSONObject(i);
			Map<String,String> map = new HashMap<String,String>();
			map.put("provinceId", obj.getString("provinceId"));
			map.put("areaType", obj.getString("areaType"));
			map.put("cityId", obj.getString("cityId"));
			map.put("name", obj.getString("name"));
			map.put("pinyin", obj.getString("pinyin"));
			list.add(map);
		}
		return maizuoDao.saveMaizuoCityInfo(list);
	}
	
	public int saveMaizuoCinemaInfo(){
		List<Map<String,String>> cinemaList = new ArrayList<Map<String,String>>();
		List<Map<String,String>> list = maizuoDao.getAllMaizuoCity();
		String url = LoadProperties.getProperty("/config.properties", "maizuoCinema");
		ResponseEntity<String> resultStr=null;
		for(Map<String,String> map : list){
			System.out.println("查询城市-------"+map.get("pinyin"));
			String cityId = map.get("cityId");
			try{
				HttpHeaders requestHeaders = new HttpHeaders();  
				requestHeaders.add("Cookie", "mzCityId="+cityId);
				HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
				resultStr = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
			}catch(Exception e){
				e.printStackTrace();
				return 0;
			}
			JSONObject jsonObject=null;
			try{
				jsonObject = JSONObject.fromObject(resultStr.getBody());
			}catch(JSONException e){
				e.printStackTrace();
				System.out.println("卖座异常城市--------"+map.get("pinyin"));
			}
			if(jsonObject.getInt("status")!=0){
				System.out.println("卖座异常城市--------"+map.get("pinyin"));
			}
			JSONArray jsonArray = jsonObject.getJSONArray("data");
			for(int i = 0;i<jsonArray.size();i++){
				JSONObject cinema = jsonArray.getJSONObject(i);
				Map<String,String> cinemaMap = new HashMap<String,String>();
				cinemaMap.put("address", cinema.getString("address"));
				cinemaMap.put("businessCircle", cinema.getString("businessCircle"));
				cinemaMap.put("cinemaId", cinema.getString("cinemaId"));
				cinemaMap.put("cityId", cinema.getString("cityId"));
				cinemaMap.put("regionName", cinema.getString("regionName"));
				cinemaMap.put("tel", cinema.getString("tel"));
				cinemaMap.put("name", cinema.getString("name"));
				cinemaList.add(cinemaMap);
			}
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return maizuoDao.saveMaizuoCinemaInfo(cinemaList);
	}
	
	//根据电影id和影院id。获取价格和购票链接
	public Map<String,Map<String,String>> getPriceHref(String fyrq,String movieId,String cinemaId){
		Map<String,Map<String,String>> resultMap = new HashMap<String,Map<String,String>>();
		Map<String,String> goodsInfoMap = new HashMap<String,String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar aCalendar = Calendar.getInstance();
		try {
			aCalendar.setTime(sdf.parse(fyrq));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
		aCalendar.setTime(new Date());
		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
		int dateFlag = day2 - day1;
		String url = LoadProperties.getProperty("/config.properties", "maizuoValidForeTells")+"?cinemaId="+cinemaId+"&dateFlag="+dateFlag+"&movieId="+movieId;
		String maizuoCinemaGoodsUrl = LoadProperties.getProperty("/config.properties", "maizuoCinemaGoods")+"?cinemaId="+cinemaId;
		try{
			String resultStr = restTemplate.getForObject(maizuoCinemaGoodsUrl, String.class);
			JSONObject obj = JSONObject.fromObject(resultStr);
			JSONArray jsonArray = obj.getJSONArray("data");
			for(int i = 0;i<jsonArray.size();i++){
				JSONObject goodsInfo = jsonArray.getJSONObject(i);
				goodsInfoMap.put(goodsInfo.getString("goodsName"), goodsInfo.getString("goodsId"));
			}
		}catch(Exception e){
			return resultMap;
		}
		try{
			String resultStr = restTemplate.getForObject(url, String.class);
			JSONObject obj = JSONObject.fromObject(resultStr);
			JSONArray jsonArray = obj.getJSONArray("data");
			for(int i = 0;i<jsonArray.size();i++){
				JSONObject foretell = jsonArray.getJSONObject(i);
				String goodsId = "";
				if(foretell.getString("dimensional").equals("2D")){
					goodsId = goodsInfoMap.get("2D订座票");
					if(goodsId==null || goodsId.equals("")){
						return resultMap;
					}
				}
				if(foretell.getString("dimensional").equals("3D")){
					goodsId = goodsInfoMap.get("3D订座票");
					if(goodsId==null || goodsId.equals("")){
						return resultMap;
					}
				}
				String foretellId = foretell.getString("foretellId");
				String href = "http://www.maizuo.com/seat.htm?goodsId="+goodsId+"&foretellId="+foretellId+"&dateFlag="+dateFlag;
				String opiPrice = String.valueOf((foretell.getInt("price")+foretell.getInt("fee"))/100);
				Map<String,String> map = new HashMap<String,String>();
				map.put("href", href);
				map.put("opiPrice", opiPrice);
				String showtime = foretell.getString("showTime");
				String showtimeFormat = showtime.substring(0, 2)+":"+showtime.substring(2, 4);
				resultMap.put(showtimeFormat, map);
			}
		}catch(Exception e){
			e.printStackTrace();
			return new HashMap<String,Map<String,String>>(); 
		}
		return resultMap;
	}
	
	
}
